import * as https from 'https';
import * as vscode from 'vscode';

interface VersionInfo {
    version: {
        v: string;
        describe: string;
    };
    gonggao: string;
}

export class UpdateService {
    private static readonly UPDATE_URL = 'https://goodit.58it.cn/v.json';
    private static readonly CURRENT_VERSION = '0.0.3'; // 当前插件版本

    // 获取远程版本信息
    public static async getVersionInfo(): Promise<VersionInfo | null> {
        return new Promise((resolve) => {
            const url = new URL(this.UPDATE_URL);
            const options = {
                hostname: url.hostname,
                path: url.pathname,
                method: 'GET',
                timeout: 5000, // 5秒超时
                headers: {
                    'User-Agent': 'GoodName-VSCode-Extension'
                }
            };

            const req = https.request(options, (res) => {
                let data = '';

                res.on('data', (chunk) => {
                    data += chunk;
                });

                res.on('end', () => {
                    try {
                        const versionInfo: VersionInfo = JSON.parse(data);
                        resolve(versionInfo);
                    } catch (error) {
                        console.error('解析版本信息失败:', error);
                        resolve(null);
                    }
                });
            });

            req.on('error', (error) => {
                console.error('获取版本信息失败:', error);
                resolve(null);
            });

            req.on('timeout', () => {
                console.error('获取版本信息超时');
                req.destroy();
                resolve(null);
            });

            req.end();
        });
    }

    // 检查是否有新版本
    public static async checkForUpdates(showNoUpdateMessage: boolean = false): Promise<void> {
        try {
            const versionInfo = await this.getVersionInfo();
            if (!versionInfo) {
                if (showNoUpdateMessage) {
                    vscode.window.showErrorMessage('无法检查更新，请检查网络连接');
                }
                return;
            }

            const remoteVersion = versionInfo.version.v;
            const currentVersion = this.CURRENT_VERSION;

            if (this.compareVersions(remoteVersion, currentVersion) > 0) {
                // 有新版本
                const action = await vscode.window.showInformationMessage(
                    `🎉 发现新版本 v${remoteVersion}！\n\n${versionInfo.version.describe}`,
                    '立即更新',
                    '查看详情',
                    '稍后提醒'
                );

                if (action === '立即更新') {
                    vscode.env.openExternal(vscode.Uri.parse('https://marketplace.visualstudio.com/items?itemName=goodname'));
                } else if (action === '查看详情') {
                    this.showUpdateDetails(versionInfo);
                }
            } else {
                if (showNoUpdateMessage) {
                    vscode.window.showInformationMessage(`✅ 当前已是最新版本 v${currentVersion}`);
                }
            }
        } catch (error) {
            console.error('检查更新失败:', error);
            if (showNoUpdateMessage) {
                vscode.window.showErrorMessage('检查更新失败，请稍后重试');
            }
        }
    }

    // 显示公告
    public static async showAnnouncement(): Promise<void> {
        try {
            const versionInfo = await this.getVersionInfo();
            if (!versionInfo) {
                vscode.window.showErrorMessage('无法获取公告信息，请检查网络连接');
                return;
            }

            if (versionInfo.gonggao && versionInfo.gonggao.trim()) {
                vscode.window.showInformationMessage(
                    `📢 GoodName 公告\n\n${versionInfo.gonggao}`,
                    '我知道了',
                    '检查更新'
                ).then(action => {
                    if (action === '检查更新') {
                        this.checkForUpdates(true);
                    }
                });
            } else {
                vscode.window.showInformationMessage('📢 暂无新公告');
            }
        } catch (error) {
            console.error('获取公告失败:', error);
            vscode.window.showErrorMessage('获取公告失败，请稍后重试');
        }
    }

    // 显示更新详情
    private static showUpdateDetails(versionInfo: VersionInfo): void {
        const panel = vscode.window.createWebviewPanel(
            'gooditname.updateDetails',
            'GoodName 更新详情',
            vscode.ViewColumn.One,
            {
                enableScripts: true
            }
        );

        panel.webview.html = this.getUpdateDetailsHTML(versionInfo);
    }

    // 生成更新详情HTML
    private static getUpdateDetailsHTML(versionInfo: VersionInfo): string {
        return `
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>更新详情</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: var(--vscode-foreground);
            background-color: var(--vscode-editor-background);
            padding: 20px;
            margin: 0;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .version {
            font-size: 2em;
            color: var(--vscode-textLink-foreground);
            margin-bottom: 10px;
        }
        .description {
            font-size: 1.2em;
            margin-bottom: 20px;
        }
        .announcement {
            background-color: var(--vscode-textBlockQuote-background);
            border-left: 4px solid var(--vscode-textLink-foreground);
            padding: 15px;
            margin: 20px 0;
            border-radius: 4px;
        }
        .update-btn {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px;
        }
        .update-btn:hover {
            background-color: var(--vscode-button-hoverBackground);
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="version">🎉 GoodName v${versionInfo.version.v}</div>
        <div class="description">${versionInfo.version.describe}</div>
    </div>
    
    ${versionInfo.gonggao ? `
    <div class="announcement">
        <h3>📢 最新公告</h3>
        <p>${versionInfo.gonggao}</p>
    </div>
    ` : ''}
    
    <div style="text-align: center; margin-top: 30px;">
        <button class="update-btn" onclick="updateNow()">立即更新</button>
    </div>
    
    <script>
        function updateNow() {
            // 通过VSCode API打开更新链接
            const vscode = acquireVsCodeApi();
            vscode.postMessage({
                command: 'openUpdateLink'
            });
        }
        
        // 监听来自扩展的消息
        window.addEventListener('message', event => {
            const message = event.data;
            if (message.command === 'openUpdateLink') {
                // 这里可以添加更多逻辑
            }
        });
    </script>
</body>
</html>`;
    }

    // 比较版本号
    private static compareVersions(version1: string, version2: string): number {
        const v1parts = version1.split('.').map(Number);
        const v2parts = version2.split('.').map(Number);
        const maxLength = Math.max(v1parts.length, v2parts.length);

        for (let i = 0; i < maxLength; i++) {
            const v1 = v1parts[i] || 0;
            const v2 = v2parts[i] || 0;

            if (v1 > v2) return 1;
            if (v1 < v2) return -1;
        }

        return 0;
    }

    // 自动检查更新（在插件激活时调用）
    public static async autoCheckUpdates(): Promise<void> {
        // 检查上次检查时间，避免频繁检查
        const config = vscode.workspace.getConfiguration('snakecasepro');
        const lastCheck = config.get<number>('lastUpdateCheck', 0);
        const now = Date.now();
        const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数

        if (now - lastCheck > oneDay) {
            // 超过一天没检查，进行自动检查
            await config.update('lastUpdateCheck', now, vscode.ConfigurationTarget.Global);
            await this.checkForUpdates(false); // 静默检查，只在有更新时提示
        }
    }
} 